<?php

/**
 * Name: 签到系统定时任务
 * User: Silent
 * Date: 2025-11-07
 * Time: 17:30:00
 */

namespace App\Console\Commands;

use App\Services\Checkin\DutyService;
use App\Services\Checkin\NotificationService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckinScheduleCommand extends Command
{
    /**
     * 命令名称和签名
     *
     * @var string
     */
    protected $signature = 'checkin:schedule {action}';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '签到系统定时任务处理';

    protected $dutyService;
    protected $notificationService;

    public function __construct(
        DutyService $dutyService,
        NotificationService $notificationService
    ) {
        parent::__construct();
        $this->dutyService = $dutyService;
        $this->notificationService = $notificationService;
    }

    /**
     * 执行命令
     *
     * @return int
     */
    public function handle()
    {
        $action = $this->argument('action');

        switch ($action) {
            case 'auto-generate-duty':
                return $this->autoGenerateDutyLeaders();
            default:
                $this->error('未知的任务类型: ' . $action);
                $this->info('可用的任务类型:');
                $this->info('  auto-generate-duty    - 自动生成下一工作日当班班长');
                return 1;
        }
    }

    /**
     * 自动生成下一工作日当班班长
     */
    private function autoGenerateDutyLeaders()
    {
        $this->info('开始自动生成下一工作日当班班长...');

        try {
            $result = $this->dutyService->autoGenerateNextWorkday();

            if ($result['success']) {
                $count = count($result['data']);
                $this->info("成功生成 {$count} 个当班班长记录");

                Log::info('自动生成当班班长成功', [
                    'count' => $count,
                    'data' => $result['data']
                ]);

                return 0;
            } else {
                $this->error('生成失败: ' . $result['message']);
                Log::error('自动生成当班班长失败', ['message' => $result['message']]);
                return 1;
            }

        } catch (\Exception $e) {
            $this->error('生成过程中发生异常: ' . $e->getMessage());
            Log::error('自动生成当班班长异常', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return 1;
        }
    }
}
